/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.grid;

import com.blandware.atleap.webapp.form.core.SetFilterForm;
import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;
import com.blandware.atleap.webapp.taglib.core.grid.util.SetFilter;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>Calls set filter JSP and sets form bean properties according to filter stored in session
 * </p>
 * <p><a href="CallSetFilterAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.14 $ $Date: 2008/05/23 08:09:15 $
 * @struts.action path="/grid/callSetFilter"
 * name="setFilterForm"
 * scope="request"
 * @struts.action-forward name="showFilterPage"
 * path=".setFilter"
 * @struts.action-forward name="filterError"
 * path=".filterError"
 */
public final class CallSetFilterAction extends BaseGridAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession();

		SetFilterForm setFilterForm = (SetFilterForm) form;
		String fieldName = setFilterForm.getFieldName();
		String gridName = setFilterForm.getGridName();
		String beanId = setFilterForm.getBeanId();
		String methodName = setFilterForm.getMethod();

		Grid grid = getGridByName(gridName, session);

		if ( grid == null ) {
			if ( log.isWarnEnabled() ) {
				String errorMessage = "No grid with name " + gridName + " could be found in session";
				log.warn(errorMessage);
			}
			return mapping.findForward("filterError");
		}
		boolean beanIdSpecified = beanId != null && beanId.length() != 0;
		boolean methodNameSpecified = methodName != null && methodName.length() != 0;

		Object c = null;
		Collection collection = null;
		Map availableElements = new HashMap();
		boolean isMap = false;
		if ( beanIdSpecified && methodNameSpecified ) {

			// Find bean in application context and specified method on it

			Object bean = getBean(beanId);
			if ( bean == null ) {
				String errorMessage = "No bean with ID=" + beanId + " could be found in application context";
				if ( log.isErrorEnabled() ) {
					log.error(errorMessage);
				}
				JspException e = new JspException(errorMessage);
				throw e;
			}

			Method method = null;
			try {
				method = bean.getClass().getMethod(methodName, (Class[]) null);
			} catch ( NoSuchMethodException e ) {
				if ( log.isErrorEnabled() ) {
					log.error(e.getMessage());
				}
				throw new JspException(e);
			}

			// Invoke method in order to get collection for displaying on set filter page

			try {
				collection = (Collection) method.invoke(bean, (Object[]) null);
			} catch ( Exception e ) {
				if ( log.isErrorEnabled() ) {
					log.error("Exception: " + e.getClass().getName() + ": " + e.getMessage());
				}
				throw new JspException(e);
			}

		} else {
			c = session.getAttribute(SetFilter.AVAILABLE_ELEMENTS);
			if ( c instanceof Map ) {
				availableElements = (Map) c;
				isMap = true;
			}
		}

		// if there was attribute in session and it was not a map, fill map from collection
		if ( !isMap ) {
			// check how collection was acquired: from persistence layer or from session atribute
			if ( collection == null ) {
				// collection was saved in session
				if ( c instanceof Collection ) {
					collection = (Collection) c;
				} else if ( c instanceof Object[] ) {
					collection = Arrays.asList((Object[]) c);
				}
			}

			String labelProperty = setFilterForm.getLabel();
			String valueProperty = setFilterForm.getValue();

			// create map of elements from collection
			for ( Iterator i = collection.iterator(); i.hasNext(); ) {
				Object nextElement = i.next();
				String label = new String();
				String value = new String();
				if ( valueProperty != null && valueProperty.length() > 0 ) {
					// value is specified
					value = String.valueOf(PropertyUtils.getProperty(nextElement, valueProperty));
					if ( labelProperty != null && labelProperty.length() > 0 ) {
						label = String.valueOf(PropertyUtils.getProperty(nextElement, labelProperty));
					} else {
						label = value;
					}
				} else {
					label = String.valueOf(nextElement);
					value = String.valueOf(nextElement);
				}
				availableElements.put(value, label);
			}
		}


		session.setAttribute(SetFilter.AVAILABLE_ELEMENTS, availableElements);

		SetFilter filter = null;
		try {
			filter = (SetFilter) grid.getFilterByFieldName(fieldName);
		} catch ( ClassCastException e ) {
			if ( log.isErrorEnabled() ) {
				String errorMessage = "Filter for field \'" + fieldName + "\' in grid \'" + gridName + "\' is not instance of com.blandware.atleap.webapp.taglib.core.grid.util.SetFilter";
				log.error(errorMessage);
			}
			return mapping.findForward("filterError");
		}

		if ( filter != null ) {
			try {
				String rowIterators = setFilterForm.getRowIterators();
				WebappUtil.copyProperties(setFilterForm, filter, request);
				setFilterForm.setRowIterators(rowIterators);
			} catch ( Exception e ) {
				if ( log.isErrorEnabled() ) {
					log.error(e);
				}
				throw new JspException(e);
			}
		}

		if ( log.isDebugEnabled() ) {
			log.debug("Returning filter page: " + mapping.findForward("showFilterPage").getPath());
		}

		return mapping.findForward("showFilterPage");
	}
}